﻿@using Chalmers.Summon;
@inherits umbraco.MacroEngines.DynamicNodeContext

@*
    Simple example of how to work with the SummonUmbraco dynamic version 1.1.0.
    Taken from Chalmers Library database search page.
    There are a number of Dictionary Items used in the code.
    The base Query String is also in a Dictionary Item but an example is provided in the comments below.
    (c) 2013 Chalmers University of Technology.
*@

@{
    // The query string is taken from QueryString "query":
    string query = (String.IsNullOrEmpty(Request.QueryString["query"]) ? "" : Request.QueryString["query"]);

    // The filter nodeId is taken from QueryString "filter":
    string filter = (String.IsNullOrEmpty(Request.QueryString["filter"]) ? "" : Request.QueryString["filter"]);

    // Double UrlEncode the query, so "adam & eve" => "adam+%2526+eve" and before Query.GetItems UrlDecode => "adam %26 eve"
    string summonQuery = umbraco.library.UrlEncode(umbraco.library.UrlEncode(query));
    
    // Here we set the Query String to Summon, were we include facets and filter on ContentType:
    // Example starting queryString: "s.dym=true&s.fvf=ContentType,Database&s.ho=true&s.role=Authenticated&s.ff=SubjectTerms,or,1,25&s.q="
    string queryString = Request.QueryString["queryString"] != null ? umbraco.library.UrlEncode(Request.QueryString["queryString"]) : umbraco.library.GetDictionaryItem("SearchDatabaseSummonQueryStringBase") + summonQuery;
    
    // Start of "searchResult" div for result page
    <div class="searchResult database">
    
        @* Try a query, catch error messages and display to user *@
        @try
        {
            // Send the query to Summon API using empty or QueryString "sessionId" Session Id:
            foreach (dynamic item in Query.GetItems(HttpUtility.UrlDecode(queryString), Request.QueryString["sessionId"]))
            {
                // Print some debug if the user want it
                if (Request.QueryString["debug"] == "1")
                {
                    <div class="alert" style="margin:28px;">
                        <h4>Debug Information for us Experts</h4>
                        SearchJournalsSummonQueryStringBase: <strong>@Dictionary["SearchJournalsSummonQueryStringBase"]</strong><br />
                        umbracoQueryString: <strong>@queryString</strong><br />
                        summonTranslatedQuerystring: <strong>@item.query.queryString</strong><br />
                        sessionId: <strong>@item.SessionId</strong><br />
                        totalRequestTime: <strong>@item.totalRequestTime ms</strong>
                    </div>
                }

                @* Hit counters *@
                <div class="searchHits">
                    @{
                        if (item.pageCount > 0) 
                        {
                            int recordEnd;
                            int recordStart = ((Convert.ToInt32(item.query.pageNumber) - 1) * Convert.ToInt32(item.query.pageSize)) + 1;
                            if (Convert.ToInt32(item.recordCount) < Convert.ToInt32(item.query.pageSize))
                            {
                                recordEnd = Convert.ToInt32(item.recordCount);
                            }
                            else
                            {
                                if (Convert.ToInt32(item.query.pageNumber) * Convert.ToInt32(item.query.pageSize) > Convert.ToInt32(item.recordCount))
                                {
                                    recordEnd = Convert.ToInt32(item.recordCount);
                                }
                                else
                                {
                                    recordEnd = Convert.ToInt32(item.query.pageNumber) * Convert.ToInt32(item.query.pageSize);
                                }
                            }
                            string countMessage = umbraco.library.GetDictionaryItem("SearchDatabaseResultMessage");
                            countMessage = countMessage.Replace("#recordStart#", recordStart.ToString());
                            countMessage = countMessage.Replace("#recordEnd#", recordEnd.ToString());
                            countMessage = countMessage.Replace("#recordCount#", item.recordCount.ToString());
                            countMessage = countMessage.Replace("#query#", query.ToString());
                            @Html.Raw(countMessage);
                        }
                        else 
                        {
                            if (item.didYouMeanSuggestions.Length > 0) {
                                foreach (dynamic suggestion in item.didYouMeanSuggestions) {
                                    string zeroSuggestMessage = umbraco.library.GetDictionaryItem("SearchDatabaseResultZeroSuggestMessage");
                                    zeroSuggestMessage = zeroSuggestMessage.Replace("#query#", query.ToString());
                                    zeroSuggestMessage = zeroSuggestMessage.Replace("#suggestedQuery#", suggestion.suggestedQuery);
                                    zeroSuggestMessage = zeroSuggestMessage.Replace("#suggestedQueryUrl#", "?filter=" + filter + "&query=" + suggestion.suggestedQuery);
                                    @Html.Raw(zeroSuggestMessage);
                                }
                            }
                            else {
                                string zeroMessage = umbraco.library.GetDictionaryItem("SearchDatabaseResultZeroMessage");
                                zeroMessage = zeroMessage.Replace("#query#", query.ToString());
                                @Html.Raw(zeroMessage);
                            }
                        }
                    }
                </div>

                @* Search filter (Summon facets) *@
                if (item.facetFields.Length > 0) 
                {
                    <div class="searchFilter">
                        <div class="category">
                            <div class="filterInfo">
							    @{
                                    foreach (dynamic facetField in item.facetFields) 
                                    {
                                        string facetCountMessage = umbraco.library.GetDictionaryItem("SearchDatabaseSubjectCount");
                                        facetCountMessage = facetCountMessage.Replace("#itemHits#", facetField.counts.Length.ToString());
                                        @Html.Raw(facetCountMessage);
                                    }
							    }
                            </div>
                            <div class="filterTags">
                                <a href="#" class="expand">
                                    @umbraco.library.GetDictionaryItem("SearchDatabaseSubjectExpand");
                                    <i class="icon-navigatedown"></i>
                                </a>
                                <ul>
                                    @* Loop trough all facets we get in the Summon Result *@
                                    @foreach (dynamic facet in item.facetFields)
                                    {
                                        @* Read the value and count in each facet *@
                                        foreach (dynamic count in facet.counts)
                                        {
                                            @* applyCommand saknas, removeCommand finns, länka upp facetten med removeCommand *@
                                            if (String.IsNullOrEmpty(count.applyCommand))
                                            {
                                                <li>
                                                    <a class="active" href="?filter=@(filter)&sessionId=@(item.sessionId)&query=@(umbraco.library.UrlEncode(query))&queryString=@(umbraco.library.UrlEncode(item.query.queryString))%26s.cmd=@(umbraco.library.UrlEncode(umbraco.library.UrlEncode(count.removeCommand)))">@count.value <span>@count.count</span></a>
                                                </li>
                                            }
                                            @* applyCommand finns, länka upp facetten med applyCommand *@
                                            else 
                                            {
                                                <li>
                                                    <a href="?filter=@(filter)&sessionId=@(item.sessionId)&query=@(umbraco.library.UrlEncode(query))&queryString=@(umbraco.library.UrlEncode(item.query.queryString))%26s.cmd=@(umbraco.library.UrlEncode(umbraco.library.UrlEncode(count.applyCommand)))">@count.value <span>@count.count</span></a>
                                                </li>
                                            }
                                        }
                                    }
                                </ul>
                            </div>
                        </div>
                    </div>
                }
     
                @* Loop trough the documents we get *@

                <ul class="searchResultList">
                    @foreach (dynamic doc in item.documents)
                    {
                        <li>
                            <div class="link">
                                <a href="@doc.link">@Html.Raw(doc.Title[0].Replace("h>", "strong>"))@(doc.Subtitle != null ? Html.Raw(": " + doc.Subtitle[0].Replace("h>", "strong>")) : "")</a>
                                <!-- <div class="issn"></div> -->
                                <ul class="tabs">
                                    <li class="active">
                                        <a href="#tab1-1" class="tabItem">@umbraco.library.GetDictionaryItem("SearchResultDatabaseTabAbstract")</a>
                                    </li>
                                    <li>
                                        <a href="#tab2-1" class="tabItem">@umbraco.library.GetDictionaryItem("SearchResultDatabaseTabLicense")</a>
                                    </li>
                                    <li>
                                        <a href="#tab3-1" class="tabItem">@umbraco.library.GetDictionaryItem("SearchResultDatabaseTabDatabasetype")</a>
                                    </li>
                                </ul>
                                <div class="tabItems">
                                    <div id="tab1-1" class="tabItem active">
                                        @if (doc.AbstractList != null) {
                                            @doc.AbstractList[0]
                                        }
                                        else {
                                            if (doc.Snippet != null) {
                                                @doc.Snippet[0]
                                            }
                                            else
	                                        {
                                                @Html.Raw(umbraco.library.GetDictionaryItem("SearchResultDatabaseMissingAbstract"))
	                                        }
                                        }
                                        <a href="#" class="expandTabsContent">@umbraco.library.GetDictionaryItem("SearchResultDatabaseShowMore") <i class="icon-navigatedown"></i></a>
                                    </div>
                                    <div id="tab2-1" class="tabItem">
                                        @Html.Raw(umbraco.library.GetDictionaryItem("SearchResultDatabaseLicense"))
                                    </div>
                                    <div id="tab3-1" class="tabItem">
										@if (doc.Genre != null) {
                                        	@doc.Genre[0]
										}else{
											@Html.Raw(umbraco.library.GetDictionaryItem("SearchResultDatabaseMissingDatabasetype"))
										}
									</div>
                                </div>
                            </div>
                            <div class="subject">
                                <span>@umbraco.library.GetDictionaryItem("SearchResultDatabaseSubject")</span>
                                <div>
                                    <ul>
                                        @if (doc.SubjectTerms != null) 
                                        {
                                            foreach (var term in doc.SubjectTerms) 
                                            {
                                                <li><a href="?filter=@(filter)&sessionId=@(item.sessionId)&query=SubjectTerms%3A%27@(umbraco.library.UrlEncode(term))%27">@term</a></li>
                                            }
                                        }
                                    </ul>
                                    <a href="#" class="expandSubject">@umbraco.library.GetDictionaryItem("SearchResultDatabaseShowMore") <i class="icon-navigatedown"></i></a>
                                </div>
                            </div>
                        </li>
                    }
                </ul>
            
                if (item.pageCount > 1) 
                {
                    @pageLinks(item.sessionId, filter, query, item.query.queryString, Convert.ToInt32(item.query.pageNumber), Convert.ToInt32(item.pageCount), 5);
                }
       }
    }
    catch (Exception e)
    {
        <div class="searchHits">
            <h1>Ett fel har uppstått:</h1>
            <p>@e.Message</p>
        </div>
        // throw;
    }

    </div> 
}

@helper pageLinks(string sessionId, string filter, string query, string queryString, int currentPage, int maxPage, int visiblePages) {
        
    // Initialize counters
	int startPage = 1;
	int endPage = startPage + (visiblePages - 1);
	
    if (maxPage > visiblePages) {
        if (currentPage <= ((visiblePages / 2) + 1))
        {
            startPage = 1;
            endPage = visiblePages;
        }
        else if (currentPage >= (maxPage - 2)) {
            startPage = maxPage - (visiblePages - 1);
            endPage = maxPage;
        }
        else {
            startPage = currentPage - (visiblePages / 2);
            endPage = currentPage + (visiblePages / 2);
        }
    }
    else {
        startPage = 1;
        endPage = maxPage;
    }
    
    <div class="pagination pagination-centered">
        <ul>
            <li class='@(currentPage == 1 ? "disabled" : "")'>
                <a href="?filter=@(filter)&sessionId=@(sessionId)&query=@(umbraco.library.UrlEncode(query))&queryString=@(umbraco.library.UrlEncode(queryString))%26s.cmd=previousPage()">
                    @umbraco.library.GetDictionaryItem("SearchResultPaginatePrevious")
                    <i class="icon-navigateleft"></i>
                </a>
            </li>
            @for (int i = startPage; i <= endPage; i++) {
                <li data-i="@i" data-current-page="@currentPage" class='@(i == currentPage ? "active" : "")'>
                    <a href="?filter=@(filter)&sessionId=@(sessionId)&query=@(umbraco.library.UrlEncode(query))&queryString=@(umbraco.library.UrlEncode(queryString))%26s.cmd=goToPage(@(i))">@i</a>
                </li>
            }
            <li class='@(currentPage == maxPage ? "disabled" : "")'>
                <a href="?filter=@(filter)&sessionId=@(sessionId)&query=@(umbraco.library.UrlEncode(query))&queryString=@(umbraco.library.UrlEncode(queryString))%26s.cmd=nextPage()">
                    @umbraco.library.GetDictionaryItem("SearchResultPaginateNext")
                    <i class="icon-navigateright"></i>
                </a>
            </li>
        </ul>
    </div>
}
